﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Mvc;
using MvcEngine.Mvc.Models.ViewModels;
using MvcEngine.Mvc.Extensions;
using MvcEngine.Core.Exceptions;
using MvcEngine.Core;
using MvcEngine.Gallery.Models;
using MvcEngine.Gallery.Managers;

namespace MvcEngine.Gallery.BackOffice.Filters
{
    public class GalleryActionFilter : IActionFilter
    {
        public void OnActionExecuted(ActionExecutedContext filterContext)
        {

        }

        public void OnActionExecuting(ActionExecutingContext filterContext)
        {
            GalleryData gallery = null;
            string galleryName = (string)filterContext.RequestContext.RouteData.Values["galleryName"];
            if (!string.IsNullOrEmpty(galleryName)) 
            {
                gallery = GalleryManager.Current.GetGallery(galleryName);
            }

            if (filterContext.RequestContext.RouteData.Values["galleryId"] != null)
            {
                string galleryId = filterContext.RequestContext.RouteData.Values["galleryId"].ToString();
                if (!string.IsNullOrEmpty(galleryId))
                {
                    gallery = GalleryManager.Current.GetGallery(new Guid(galleryId));
                }
            }

            if (gallery != null)
            {
                filterContext.ActionParameters["galleryId"] = gallery.Id;
                filterContext.ActionParameters["galleryName"] = gallery.Name;
                filterContext.RequestContext.RouteData.Values["galleryId"] = gallery.Id;
                filterContext.RequestContext.RouteData.Values["galleryName"] = gallery.Name;
            }
        }
    }
}
